from flask import Blueprint,request,make_response,jsonify

from util.captcha.captcha import captcha
import json, random, time, requests

from util.comd5 import md5
from util.myjwt import myjwt
from util.myredis import r
from models.user import *

user_blue = Blueprint("userblue",__name__)


@user_blue.route("/getImageCode")
def getImageCode():
    # 生成图片验证码 text文字   image图片流
    name, text, image = captcha.generate_captcha()
    # 从页面获取uuid做为redis key
    uuid = request.args.get("uuid")
    # 存入redis
    r.str_setex(uuid, text, 300)
    # 以流的方式生成图片验证码
    res = make_response(image)
    res.headers["Content-Type"] = 'image/jpg'
    return res

@user_blue.route('/login',methods=['POST'])
def login():
    data = json.loads(request.data)
    mobile = data['mobile']
    password = data['pwd']
    res = Admin_User.query.filter_by(mobile=mobile).first()
    if res:
        if password == res.password:
            data = {'data': {'user_id': res.id, "mobile": res.mobile, 'exp': int(time.time()),'role_id': res.role_id}}
            token = myjwt.jwt_encode(data)
            res = db.session.execute("select re.*,pre.name as pname from role_resource as rr left join resource as re on rr.resource_id=re.id left join resource as pre on pre.id = re.pid where rr.role_id=%d and re.type=1" % int(
                data['data']['role_id']))
            # 新建list列表,遍历列表res，将父类放入list列表中
            list = []
            idlist = []
            pomitionlist = []
            getresourceurl = GetResourceurl(data['data']['role_id'])
            key = "role_id" + str(data['data']['role_id'])
            r.str_add(key,json.dumps(getresourceurl))
            for i in res:
                print('>>>>>',i)
                pomitionlist.append(i.url)
                if i.pid not in idlist:
                    list.append({'id': i.pid, 'name': i.pname, 'son': []})
                    print("5656",list)
                    idlist.append(i.pid)
            # 遍历res，将子类和父类list进行对比，如果相同方法哦son，son.append
            for j in res:
                for index, p in enumerate(list):
                    if j.pid == p['id']:
                        list[index]['son'].append({'id': j['id'], 'name': j['name'], 'url': j['url']})
            return  jsonify({
                'code': 200,
                'msg': "登陆成功",
                'user_id': data['data']['user_id'],
                'token': token,
                'role_id': data['data']['role_id'],
                'list': list,
                'pomitionlist': pomitionlist,
            })
        else:
            return jsonify({
                'code': 400,
                'msg': "密码错误"
            })
    else:
        admin_user = Admin_User(mobile=mobile,password=password,role_id=1)
        db.session.add(admin_user)
        db.session.commit()
        return jsonify({
            'code':201,
            'msg':"已注册请您重新登录"
        })

def GetResourceurl(role_id):
    res = db.session.execute("""select res.url from role_resource as rr left join resource as res on rr.resource_id=res.id where rr.role_id=%d and type=2"""%int(role_id))
    list = []
    for i in res:
        list.append(i.url)
    return list



@user_blue.route('/get_server_audit')
def get_server_audit():
    role_id = request.args.get('role_id')
    q1 = db.session.query(Server).filter(Server.status == 0, Server.role_id == int(role_id))
    q2 = db.session.query(Server1).filter(Server1.status == 0, Server1.role_id == int(role_id))
    q3 = db.session.query(Server2).filter(Server2.status == 0, Server2.role_id == int(role_id))
    ret = q1.union(q2).union(q3).all()
    lst = []
    for i in ret:
        lst.append({
            'id': str(i.code),
            'title': i.title,
            'user_id': i.user_id,
            'type': i.type,
            'desc': i.desc,
            'label': i.label,
            'budget': float(i.budget),
            'mobile': i.mobile,
            'status': i.status,
            'create_time': str(i.create_time)
        })
    return jsonify({
        'code':200,
        'msg':"OK",
        'data':lst
    })


@user_blue.route('/audit_server')
def audit_server():
    code = request.args.get('code')
    title = "Server"
    number = hash(int(code))%3
    if number != 0:
        title = title + str(number)
    title = globals().get(f'{title}')
    server = title.query.filter_by(code=code).first()
    use = Users.query.filter_by(id=server.user_id).first()
    try:
        if use:
            use.money = float(use.money) - float(server.budget)
            use.lock_moeny = float(use.lock_moeny) + float(server.budget)
            db.session.add(use)
        else:
            return jsonify({
                'code':400,
                'msg':"请重新登录"
            })
        if server:
            server.status = 1
            db.session.add(server)
        else:
            return jsonify({
                'code': 400,
                'msg': "数据不存在"
            })
        db.session.commit()
        return jsonify({
            'code': 200,
            'msg': "审核成功"
        })
    except Exception as e:
        print(e)
        return jsonify({
            'code':400,
            'msg':"后端错误"
        })

# select re.*,pre.name as pname from role_resource as rr left join resource as re on rr.resource_id=re.id left join resource as pre on pre.id = re.pid where rr.role_id=2 and re.type=1